<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/util/axios";

const ruleForm = ref({
  username: "",
  oldPassword: "",
  newpassword: "",
  newpassword2: "",
});

const rules = ref({
  username: [{ required: true, message: "请输入用户名" }],
  oldPassword: [{ required: true, message: "请输入原密码" }],
  newpassword: [{ required: true, message: "请输入新密码" }],
  newpassword2: [{ required: true, message: "请输入确认密码" }],
});

const ruleFormRef = ref(null);

//显示当前登录的用户名，需要先在login登录下添加 window.sessionStorage.setItem("user",JSON.stringify(form.value))
const initFormData = () => {
  let user = window.sessionStorage.getItem("user");
  ruleForm.value = JSON.parse(user);
};
initFormData();

const onsubmit = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log("success");
      if (ruleForm.value.oldPassword !== ruleForm.value.password) {
        ElMessage.error("原密码错误！");
      } else if (ruleForm.value.newPassword !== ruleForm.value.newPassword2) {
        ElMessage.error("确认新密码错误！");
      } else {
        try {
          let result = await axios.post("admin/modifyPassword", ruleForm.value);
          let data = result.data;
          if (data.code == 0) {
            ElMessage.success("密码修改成功，重新登录后生效！");
            ruleFormRef.value.resetFields();
          } else {
            ElMessage.error(data.msg);
          }
        } catch (err) {
          console.log(err);
          ElMessage.error("系统运行出错，请联系管理员！");
        }
      }
    } else {
      console.log("fail");
      return false;
    }
  });
};
</script>

<template>
  <el-card>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="150px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" disabled />
      </el-form-item>

      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="ruleForm.oldPassword" type="password" />
      </el-form-item>

      <el-form-item label="新密码" prop="newpassword">
        <el-input v-model="ruleForm.newpassword" type="password" />
      </el-form-item>

      <el-form-item label="确认新密码" prop="newpassword2">
        <el-input v-model="ruleForm.newpassword2" type="password" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onsubmit">确认修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.el-input {
  width: 300px;
}
</style>